package com.example.dnfgamercommunitybackend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.dnfgamercommunitybackend.entity.Account;
import com.example.dnfgamercommunitybackend.entity.LoginAccount;
import com.example.dnfgamercommunitybackend.entity.ResponseResult;
import com.example.dnfgamercommunitybackend.service.AuthorizationService;
import com.example.dnfgamercommunitybackend.util.JwtUtil;
import com.example.dnfgamercommunitybackend.util.RedisUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Service
public class AuthorizationServiceImpl implements AuthorizationService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private JwtUtil jwtUtil;
    @Override
    public String login(Account account) {
        //包装用户名和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(account.getUsername(),account.getPassword());
        //认证用户名和密码
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        //如果认证失败，抛出异常
        if (Objects.isNull(authentication)){
            throw new RuntimeException("账号或密码错误");
        }else{
            //认证通过，获取用户信息
            LoginAccount loginAccount = (LoginAccount) authentication.getPrincipal();
            //将用户信息保存到redis中
            redisUtil.set("login:"+loginAccount.getAccount().getId(),loginAccount);
            //生成token
            String token = jwtUtil.createToken(loginAccount.getAccount().getId());
            Map<String,Object> tokenMap = new HashMap<>();
            tokenMap.put("token",token);
            tokenMap.put("role",loginAccount.getAccount().getRole());
            tokenMap.put("userId",loginAccount.getAccount().getId());
            return JSONObject.toJSONString(ResponseResult.success("登录成功",tokenMap));
        }
    }

    @Override
    public String logout() {
        //从SecurityContextHolder中获取用户信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginAccount loginAccount  = (LoginAccount) usernamePasswordAuthenticationToken.getPrincipal();
        int id = loginAccount.getAccount().getId();
        if (redisUtil.remove("login:"+id)){
            return JSONObject.toJSONString(ResponseResult.success("成功退出登录"));
        }else {
            return JSONObject.toJSONString(ResponseResult.failure(501,"退出登录异常"));
        }

    }
}
